'use strict'
const chalk =  require("chalk")
/**
 * 快捷打包部署
 */
function getTime(type = "datetime", dateOrigin) {
    var d = new Date();
    if (dateOrigin) {
        d = dateOrigin;
    }
    var year = d.getFullYear();
    var month = change(d.getMonth() + 1);
    var day = change(d.getDate());
    var hour = change(d.getHours());
    var minute = change(d.getMinutes());
    var second = change(d.getSeconds());

    function change(t) {
        if (t < 10) {
            return "0" + t;
        } else {
            return t;
        }
    }
    if (type === "datetime") {
        var datetime = year + month + day + hour + minute + second;
        return datetime;
    } else if (type === "date") {
        var date = year + "-" + month + "-" + day;
        return date;
    } else if (type === "time") {
        var time = hour + ":" + minute + ":" + second;
        return time;
    }
}

const args = process.argv.slice(2);

if (args[0]) {
    const fs = require("fs");
    const path = require("path");
    const compressing = require('compressing');
    const omapPath = path.resolve(__dirname, './package.json')
    const mpath = path.resolve(__dirname, `./dist/${args[0]}`);
    const spath = path.resolve(__dirname, `./dist/${args[0]}-${getTime('datetime', new Date())}.zip`);
    const tarStream = new compressing.zip.Stream();

    tarStream.addEntry(omapPath);
    var files = fs.readdirSync(mpath);
    Promise.all(files.map(e => {
        return new Promise((res) => {
            var tarpath = path.join(mpath, e);
            tarStream.addEntry(tarpath);
            res(true);
        })
    })).then(r => {
        tarStream
            .pipe(fs.createWriteStream(spath))
            .on('finish', err => {
                if (!err) {
                    console.log('压缩成功:', chalk.yellow(spath));
                } else {
                    console.log('err', err);
                }
            })
    })
}

